<template>
  <div p-5>
    <DynamicTable
      bordered
      :data-request="loadData"
      :columns="columns"
      row-key="id"
      @resize-column="handleResizeColumn"
      :scroll="{
        y: 'calc(100vh - 360px)',
      }"
    >
      <template #toolbar>
        <a-button type="primary" @click="openTableModal({})"> 新增 </a-button>
      </template>
    </DynamicTable>

    <a-modal
      v-model:open="open"
      title="文件预览"
      :width="800"
      :footer="null"
      :destroyOnClose="true"
    >
      <iframe :src="pdfUrl + '#toolbar=0'" width="100%" style="height: 70vh; overflow: scroll" />
    </a-modal>
  </div>
</template>
<script setup lang="ts">
  import { ref } from 'vue';

  import { Modal, message } from 'ant-design-vue';
  import { baseColumns, type TableListItem } from './columns';
  import { bookSchemas } from './formSchemas';

  import { getTableListApi, updateBook, createBook, deleteBookApi } from '@/api/base/book/index';

  import {
    useTable,
    type OnChangeCallbackParams,
    type TableColumn,
  } from '@/components/core/dynamic-table';
  import { useFormModal } from '@/hooks/useModal/index';

  import { downloadFile } from '@/api/account';

  const [showModal] = useFormModal();

  const [DynamicTable, dynamicTableInstance] = useTable();
  const columns: TableColumn[] = [
    ...baseColumns,
    {
      title: '操作',
      align: 'left',
      width: 140,
      dataIndex: 'ACTION',
      actions: ({ record }) => [
        {
          label: '查看',
          onClick: () => openInfoMoadl(record),
        },
        {
          ifShow: record.dataType === 2,
          label: '编辑',
          onClick: () => openTableModal(record),
        },
        {
          ifShow: record.dataType === 2,
          label: '删除',
          onClick: () => deleteTable(record),
        },
      ],
    },
  ];

  const loadData = async (
    params,
    onChangeParams: OnChangeCallbackParams,
  ): Promise<API.TableListResult> => {
    const data = await getTableListApi(params);
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({
          list: data,
          ...params,
        });
      }, 500);
    });
  };

  const handleResizeColumn = (w, col) => {
    col.width = w;
  };

  /**
   * @description 打开文书模板弹窗
   */
  const openTableModal = async (record: Partial<TableListItem> = {}) => {
    const [formRef] = await showModal<any>({
      modalProps: {
        title: `${record.id ? '编辑' : '新增'}文书模板`,
        width: 500,
        onFinish: async (values) => {
          values.id = record.id;
          delete values.file;
          await (record.id ? updateBook : createBook)(values);
          dynamicTableInstance?.reload();
        },
      },
      formProps: {
        labelWidth: 80,
        schemas: bookSchemas,
        autoSubmitOnEnter: true,
      },
    });

    if (record?.id) {
      // @ts-ignore
      const nameFix = record.fileUrl.split('.')[record.fileUrl.split('.').length - 1];
      record.file = [
        {
          uid: record.id,
          status: 'done',
          name: record.name + '.' + nameFix,
        },
      ];
      formRef?.setFieldsValue(record);
    }
  };

  /**
   * @description 删除文书模板
   */
  const deleteTable = (record: Partial<TableListItem> = {}) => {
    Modal.confirm({
      title: '确定删除该文书模板？',
      centered: true,
      onOk: async () => {
        await deleteBookApi(record.id);
        dynamicTableInstance?.reload?.();
      },
      onCancel: () => {},
    });
  };

  const open = ref(false);
  const pdfUrl = ref();
  const openInfoMoadl = (record) => {
    downloadFile(record.fileUrl).then((res) => {
      let blob = new Blob([res], { type: 'application/pdf' }); //文件流处理
      const url = window.URL.createObjectURL(blob);
      pdfUrl.value = url;
      open.value = true;
    });
  };
</script>
<style scoped lang="less"></style>
